from flask import request
from math import ceil
from sqlalchemy.orm import Query

class Pagination:
    def __init__(self, query, page, per_page):
        self.query = query
        self.page = page
        self.per_page = per_page
        self.total = query.count()
        self.pages = ceil(self.total / per_page) if self.total > 0 else 1

    @property
    def items(self):
        return self.query.limit(self.per_page).offset((self.page - 1) * self.per_page).all()

    @property
    def has_prev(self):
        return self.page > 1

    @property
    def has_next(self):
        return self.page < self.pages

    def iter_pages(self):
        return range(1, self.pages + 1)

# 分页功能
def paginate(query, per_page=10):
    page = request.args.get('page', 1, type=int)
    return Pagination(query, page, per_page)

# 表单验证工具
def validate_form(fields):
    errors = {}
    data = request.get_json()
    
    for field in fields:
        if field['required'] and not data.get(field['name']):
            errors[field['name']] = f"{field['label']}不能为空"
        
        if 'max_length' in field and data.get(field['name']):
            if len(data[field['name']]) > field['max_length']:
                errors[field['name']] = f"{field['label']}超过最大长度限制"
    
    return data, errors if not errors else None